package com.huposoft.littleant.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 *
 * @Auther: anin
 * @Date: 2019/12/19 16:36
 * @version : V1.0
 */
public class GetIP {
    public static String getNowIP(){
        URL url;
        try {
            url = new URL("http://chaipip.com/");//获取当前公网IP的网址
            URLConnection con = url.openConnection();//创建一个连接
            //缓存读取到的内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
            String content;
            while((content = reader.readLine()) != null){

                Pattern p1 = Pattern.compile(">您的(\\d*.\\d*.\\d*.\\d*)</div>");
                Matcher m1 = p1.matcher(content);
                while(m1.find()){
                    System.err.println("当前IP为 ["+m1.group(1)+"]");
                    return m1.group(1);
                }
            }
            reader.close();//关闭读取流
            con.connect();//关闭连接

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }



    public static void main(String[] args) {
        String nowIP = GetIP.getNowIP();
        System.out.println(nowIP);
    }
}
